import {
  View,
  Text,
  StyleSheet,
  FlatList,
  Dimensions,
  Image,
  TouchableOpacity,
} from 'react-native';
import React, { useEffect, useRef } from 'react';
import { categoryItem } from '../../models/categoryModal';
import { getCategorListyApi } from '../../apis/categoryApi';
import { flagToTree } from '../../utils/flatToTree';
import { useNavigation } from '@react-navigation/native';

// 获取屏幕视口的高度
const { height } = Dimensions.get('window');

const CategorySreen = () => {
  const [categoryList, setCategoryList] = React.useState<categoryItem[]>([]);

  const getCategoryList = async () => {
    const res = await getCategorListyApi();
    // console.log(res);
    setCategoryList(flagToTree(res));
    // setCategoryList(res.data)
  };
  const [falg, setFalg] = React.useState<boolean>(true);
  const [activeKey, setActiveKey] = React.useState<number>(1);
  // const [slideHeight, setSlideHeight] = React.useState<number>(0);
  // 使用Animated.Value来实现平滑的滑块动画

  // 左侧滑块滚动距离

  // 左侧点击事件
  const leftOnPress = (item: categoryItem) => {
    // console.log(123);
    setFalg(false);
    setActiveKey(item.id);
    const index = categoryList.findIndex(node => node.id === item.id);

    // 计算新的滑块位置
    // 每个选项高50，减去滑块自身高度的一半(7.5)使其居中显示

    // 更新状态（保持与动画同步）
    // setSlideHeight(newSlideHeight);

    rightRef.current?.scrollToIndex({
      index: index,
      animated: true,
    });
  };
  // 右侧滚动事件
  const rightScroll = (nativeEvent: any) => {
    // console.log(falg);
    if (falg) {
      const y = nativeEvent.contentOffset.y;
      // console.log(height);
      // console.log(y);
      const index = Math.floor(y / height) === -1 ? 0 : Math.floor(y / height);
      // console.log(index);

      // 确保索引在有效范围内
      if (index >= 0 && index < categoryList.length) {
        setActiveKey(categoryList[index].id);

        // 更新状态
        // setSlideHeight(newSlideHeight);
      }
    }
  };
  const navigate = useNavigation();
  // 右侧跳转事件
  const rightItemOnPress = (item: categoryItem) => {
    console.log(item);
    // 跳转到CourseList页面
    navigate.navigate('CourseList');
  };

  useEffect(() => {
    getCategoryList();
    // changeSlideHeight(activeKey);
  }, []);
  // console.log(categoryList);
  const rightRef = useRef<FlatList>(null);

  // 渲染的页面结构
  return (
    <View style={styles.container}>
      <View style={styles.left}>
        <FlatList
          data={categoryList}
          renderItem={({ item }) => (
            <LeftItem
              item={item}
              activeKey={activeKey === item.id}
              onPress={() => {
                leftOnPress(item);
              }}
            />
          )}
          keyExtractor={item => item.id.toString()}
        />
      </View>
      {/*  右侧 */}
      <View style={styles.right}>
        <FlatList
          ref={rightRef}
          data={categoryList}
          renderItem={({ item }) => (
            <RightItem item={item} rightItemOnPress={rightItemOnPress} />
          )}
          keyExtractor={item => item.id.toString()}
          onScroll={({ nativeEvent }) => {
            rightScroll(nativeEvent);
          }}
          onMomentumScrollEnd={() => {
            setFalg(true);
          }}
          scrollEventThrottle={16}
          getItemLayout={(data, index) => {
            // console.log(data);
            return {
              length: height,
              offset: height * index,
              index,
            };
          }}
        />
      </View>
    </View>
  );
};

// 定义左侧的每一项
const LeftItem = ({
  item,
  activeKey,
  onPress,
}: {
  item: categoryItem;
  activeKey: boolean;
  onPress: () => void;
}) => {
  return (
    <TouchableOpacity style={[styles.leftItem]} onPress={onPress}>
      <Text style={[styles.leftItemText, activeKey && styles.leftItemActive]}>
        {item.catname}
      </Text>
    </TouchableOpacity>
  );
};
// 定义右侧的每一项
const RightItem = ({
  item,
  rightItemOnPress,
}: {
  item: categoryItem;
  rightItemOnPress: (item: categoryItem) => void;
}) => {
  return (
    <View style={styles.rightItem}>
      <View>
        <Text style={styles.rightItemTitle}>{item.catname}</Text>
      </View>
      <View style={styles.rightItem_Grid}>
        {item.children?.map((node: categoryItem) => {
          return (
            <TouchableOpacity
              style={styles.rightItem_GridItem}
              key={node.id}
              onPress={() => rightItemOnPress(node)}
            >
              {node.icon ? (
                <Image
                  source={{ uri: node.icon }}
                  style={styles.rightItem_GridItemImg}
                />
              ) : (
                <Text style={styles.rightItem_GridItemImg}>暂无图片</Text>
              )}
              <Text style={styles.rightItem_GridItemText}>{node.catname}</Text>
            </TouchableOpacity>
          );
        })}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  leftSlide: {
    width: 5,
    height: 15,
    position: 'absolute',
    left: 0,
    backgroundColor: '#1ba5fd',
    // transform: 'translateX(-50%)'
  },
  left: {
    width: 100,
    height: '100%',
    // backgroundColor: 'red',
    position: 'relative',
  },
  leftItem: {
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
  },
  leftItemText: {
    width: '100%',

    textAlign: 'center',
  },
  leftItemActive: {
    // backgroundColor: 'pink',
    color: '#1ba5fd',
    borderLeftWidth: 5,
    borderLeftColor: '#1ba5fd',
  },

  right: {
    flex: 1,
    height: '100%',
    // backgroundColor: 'blue',
  },
  rightItem: {
    boxSizing: 'border-box',
    height: height,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  rightItemTitle: {
    lineHeight: 50,
    paddingLeft: 10,
    fontWeight: 'bold',
  },
  rightItem_Grid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    // paddingLeft: 10,
    // backgroundColor: 'red',
  },
  rightItem_GridItem: {
    width: '27%',
    height: 60,
    margin: 5,
    justifyContent: 'center',
    alignItems: 'center',
    // boxShadow: '0 0 5px #ccc',
    // backgroundColor: 'red',
  },
  rightItem_GridItemImg: {
    width: 40,
    height: 40,
    display: 'flex',
    // justifyContent: 'center',
    // alignItems: 'center',
  },
  rightItem_GridItemText: {
    textAlign: 'center',
    marginTop: 5,
    fontSize: 12,
  },
});

export default CategorySreen;
